<template>
  <!-- 非网关节点 -->
  <div class="node-wrap" v-if="['start', 'approval', 'cc'].includes(nodeConfig.type)">
    <div class="node-wrap-box" :class="(nodeConfig.type == 'start' ? 'start-node ' : '') + (isTried && nodeConfig.error ? 'active error' : '')">
      <div class="title" :style="`background: rgb(${bgColors[nodeConfig.type]});`">
        <span v-if="nodeConfig.type == 'start'">{{ nodeConfig.nodeName }}</span>
        <template v-else>
          <span class="iconfont">{{ nodeConfig.type == 'approval' ? '&#xe6db;' : '&#xe688;' }}</span>
          <input
            v-if="isInput"
            type="text"
            class="ant-input editable-title-input"
            @blur="blurEvent()"
            @focus="$event.currentTarget.select()"
            v-focus
            v-model="nodeConfig.nodeName"
            :placeholder="defaultText"
          />
          <span v-else class="editable-title" @click="clickEvent()">{{ nodeConfig.nodeName }}</span>
          <i class="iconfont close" @click="delNode">&#xeb6a;</i>
        </template>
      </div>
      <div class="content" @click="setPerson">
        <div class="text">
          <span class="placeholder" v-if="!showText">请选择{{ defaultText }}</span>
          {{ showText }}
        </div>
        <i class="iconfont arrow">&#xe645;</i>
      </div>
      <div class="error_tip" v-if="isTried && nodeConfig.error">
        <i class="iconfont exclamation-circle">&#xe60e;</i>
      </div>
    </div>
    <AddNode v-model:childNodeP="nodeConfig.childNode" :pid="nodeConfig.id" />
  </div>
  <!-- 网关节点 -->
  <div class="branch-wrap" v-if="nodeConfig.type == 'exclusive'">
    <div class="branch-box-wrap">
      <div class="branch-box">
        <button class="add-branch" @click="addTerm">添加条件</button>
        <div class="col-box" v-for="(item, index) in nodeConfig.conditionNodes" :key="index">
          <div class="condition-node">
            <div class="condition-node-box">
              <div class="auto-judge" :class="isTried && item.error ? 'error active' : ''">
                <div class="sort-left" v-if="index != 0 && !item.def" @click="arrTransfer(index, -1)">&lt;</div>
                <div class="title-wrapper">
                  <input
                    v-if="isInputList[index] && !item.def"
                    type="text"
                    class="ant-input editable-title-input"
                    @blur="blurEvent(index)"
                    @focus="$event.currentTarget.select()"
                    v-focus
                    v-model="item.nodeName"
                  />
                  <span v-else class="editable-title" @click="clickEvent(index)">{{ item.nodeName }}</span>
                  <span class="priority-title" @click="setPerson(item)">优先级{{ item.priorityLevel }}</span>
                  <i v-if="!item.def" class="iconfont close" @click="delTerm(index)">&#xeb6a;</i>
                </div>
                <div class="sort-right" v-if="index != nodeConfig.conditionNodes.length - 2 && !item.def" @click="arrTransfer(index)">&gt;</div>
                <div class="content" @click="setPerson(item)">{{ $func.conditionStr(item) }}</div>
                <div class="error_tip" v-if="isTried && item.error">
                  <i class="iconfont exclamation-circle">&#xe60e;</i>
                </div>
              </div>
              <AddNode v-model:childNodeP="item.childNode" :pid="item.id" />
            </div>
          </div>
          <NodeWrap v-if="item.childNode" v-model:nodeConfig="item.childNode" />
          <template v-if="index == 0">
            <div class="top-left-cover-line"></div>
            <div class="bottom-left-cover-line"></div>
          </template>
          <template v-if="index == nodeConfig.conditionNodes.length - 1">
            <div class="top-right-cover-line"></div>
            <div class="bottom-right-cover-line"></div>
          </template>
        </div>
      </div>
      <AddNode v-model:childNodeP="nodeConfig.childNode" :pid="nodeConfig.id" />
    </div>
  </div>
  <!-- 结束节点 -->
  <div class="end-node" v-if="nodeConfig.type == 'end'">
    <div class="end-node-circle"></div>
    <div class="end-node-text">流程结束</div>
  </div>
  <NodeWrap v-if="nodeConfig.childNode" v-model:nodeConfig="nodeConfig.childNode" />
</template>

<script setup>
import { onMounted, ref, watch, getCurrentInstance, computed } from 'vue'
import $func from '@/utils/flow'
import { useStore } from 'vuex'
import { bgColors, placeholderList } from '@/utils/flowConst'
import { generateUUID } from '@/utils/tools'

let props = defineProps({
  nodeConfig: {
    type: Object,
    default: () => ({})
  }
})
let emits = defineEmits(['update:flowPermission', 'update:nodeConfig'])

let store = useStore()
let _uid = getCurrentInstance().uid
const nodeConfig = computed(() => props.nodeConfig)
let defaultText = computed(() => {
  return placeholderList[nodeConfig.value.type]
})
let showText = computed(() => {
  if (nodeConfig.value.type == 'start') return $func.operatorToString(nodeConfig.value) || '所有人'
  if (nodeConfig.value.type == 'approval') return $func.setApproverStr(nodeConfig.value) || '请设置审批人'
  return $func.setCopyerStr(nodeConfig.value) || '请设置抄送人'
})

let isInputList = ref([])
let isInput = ref(false)
const resetConditionNodesErr = () => {
  nodeConfig.value.conditionNodes.forEach(item => {
    if (item.def) {
      item.error = false
    } else {
      item.error = $func.conditionStr(item) == '请设置条件'
    }
  })
}

let isTried = computed(() => store.state.flow.isTried)
let flowPermission1 = computed(() => store.state.flow.flowPermission1)
let approverConfig1 = computed(() => store.state.flow.approverConfig1)
let copyerConfig1 = computed(() => store.state.flow.copyerConfig1)
let conditionsConfig1 = computed(() => store.state.flow.conditionsConfig1)
watch(flowPermission1, flow => {
  if (flow.flag && flow.id === _uid) {
    emits('update:nodeConfig', flow.value)
  }
})
watch(approverConfig1, approver => {
  if (approver.flag && approver.id === _uid) {
    emits('update:nodeConfig', approver.value)
  }
})
watch(copyerConfig1, copyer => {
  if (copyer.flag && copyer.id === _uid) {
    emits('update:nodeConfig', copyer.value)
  }
})
watch(conditionsConfig1, condition => {
  if (condition.flag && condition.id === _uid) {
    emits('update:nodeConfig', condition.value)
  }
})

const clickEvent = index => {
  if (index || index === 0) {
    isInputList.value[index] = true
  } else {
    isInput.value = true
  }
}
const blurEvent = index => {
  if (index || index === 0) {
    isInputList.value[index] = false
    nodeConfig.value.conditionNodes[index].nodeName = nodeConfig.value.conditionNodes[index].nodeName || '条件'
  } else {
    isInput.value = false
    nodeConfig.value.nodeName = nodeConfig.value.nodeName || defaultText
  }
}
const delNode = () => {
  if(nodeConfig.value.childNode) {
    nodeConfig.value.childNode.pid = nodeConfig.value.pid
  }
  emits('update:nodeConfig', nodeConfig.value.childNode)
}
const addTerm = () => {
  let len = nodeConfig.value.conditionNodes.length
  nodeConfig.value.conditionNodes.splice(len - 1, 0, {
    id: generateUUID(),
    pid: nodeConfig.value.id,
    nodeName: '条件' + len,
    type: 'condition',
    error: true,
    def: false,
    priorityLevel: len,
    conditionList: [],
    childNode: null
  })
  nodeConfig.value.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1
    if (!item.def) {
      item.nodeName = `条件${index + 1}`
    }
  })
  resetConditionNodesErr()
  emits('update:nodeConfig', nodeConfig.value)
}
const delTerm = index => {
  nodeConfig.value.conditionNodes.splice(index, 1)
  nodeConfig.value.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1
    if (!item.def) {
      item.nodeName = `条件${index + 1}`
    }
  })
  resetConditionNodesErr()
  emits('update:nodeConfig', nodeConfig.value)
  // 只剩下一个条件的时候就没有分支了
  if (nodeConfig.value.conditionNodes.length == 1) {
    if (nodeConfig.value.childNode) {
      if (nodeConfig.value.conditionNodes[0].childNode) {
        reData(nodeConfig.value.conditionNodes[0].childNode, nodeConfig.value.childNode)
      } else {
        nodeConfig.value.conditionNodes[0].childNode = nodeConfig.value.childNode
      }
    }
    const { childNode } = nodeConfig.value.conditionNodes[0]
    if(childNode) {
      childNode.pid = nodeConfig.value.pid
    }
    emits('update:nodeConfig', childNode)
  }
}
const reData = (data, addData) => {
  if (!data.childNode) {
    data.childNode = addData
  } else {
    reData(data.childNode, addData)
  }
}
const setPerson = condition => {
  var { type } = nodeConfig.value
  // 发起人
  if (type == 'start') {
    store.commit('flow/setFlowPermission', {
      value: {
        ...JSON.parse(JSON.stringify(nodeConfig.value))
      },
      flag: false,
      id: _uid
    })
    store.commit('flow/setPromoter', true)
  } else if (type == 'approval') {
    store.commit('flow/setApproverConfig', {
      value: {
        ...JSON.parse(JSON.stringify(nodeConfig.value)),
        ...{ assigneeType: nodeConfig.value.assigneeType ? nodeConfig.value.assigneeType : 1 }
      },
      flag: false,
      id: _uid
    })
    store.commit('flow/setApprover', true)
  } else if (type == 'cc') {
    store.commit('flow/setCopyerConfig', {
      value: JSON.parse(JSON.stringify(nodeConfig.value)),
      flag: false,
      id: _uid
    })
    store.commit('flow/setCopyer', true)
  } else if (type == 'exclusive') {
    if (condition.def) return
    store.commit('flow/setConditionsConfig', {
      value: JSON.parse(JSON.stringify(nodeConfig.value)),
      priorityLevel: condition.priorityLevel,
      flag: false,
      id: _uid
    })
    store.commit('flow/setCondition', true)
  }
}
const arrTransfer = (index, type = 1) => {
  //向左-1,向右1
  nodeConfig.value.conditionNodes[index] = nodeConfig.value.conditionNodes.splice(index + type, 1, nodeConfig.value.conditionNodes[index])[0]
  nodeConfig.value.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1
  })
  resetConditionNodesErr()
  emits('update:nodeConfig', nodeConfig.value)
}

onMounted(() => {
  if (nodeConfig.value.type == 'approval') {
    nodeConfig.value.error = !$func.setApproverStr(nodeConfig.value)
  } else if (nodeConfig.value.type == 'cc') {
    nodeConfig.value.error = !$func.setCopyerStr(nodeConfig.value)
  } else if (nodeConfig.value.type == 'exclusive') {
    resetConditionNodesErr()
  }
})
</script>
<style lang="scss" scoped>
.error_tip {
  position: absolute;
  top: 0px;
  right: 0px;
  transform: translate(150%, 0px);
  font-size: 24px;
}

.end-node {
  border-radius: 50%;
  font-size: 14px;
  color: rgba(25, 31, 37, 0.4);
  text-align: left;
}

.end-node .end-node-circle {
  width: 10px;
  height: 10px;
  margin: auto;
  border-radius: 50%;
  background: #dbdcdc;
}

.end-node .end-node-text {
  margin-top: 5px;
  text-align: center;
}
</style>
